package de.mariusharbeck.saralentz.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Component;

import de.mariusharbeck.saralentz.dao.BildDao;
import de.mariusharbeck.saralentz.entity.Bild;

@Component("bildDao")
public class BildDaoImpl extends GenericDaoImpl<Bild> implements BildDao {
	// we inherit the basic CRUD operations from the GenericRepository

	@SuppressWarnings("unchecked")
	@Override
	public List<Bild> findNewBilder() {
		final Query query = this.em
				.createQuery("SELECT b FROM Bild b WHERE b.format <> :format ORDER BY b.id DESC");
		query.setParameter("format", "counter");
		return query.getResultList();
	}

	@Override
	public synchronized void addHit(int id) {
		em.getTransaction().begin();
		final Query query = this.em
				.createQuery("SELECT b FROM Bild b WHERE b.id = :id");
		query.setParameter("id", id);
		Bild bild = (Bild) query.getSingleResult();
		bild.setHits(bild.getHits() + 1);
		em.persist(bild);
		em.getTransaction().commit();
	}

	@Override
	public void addHit() {
		em.getTransaction().begin();
		final Query query = this.em
				.createQuery("SELECT b FROM Bild b WHERE b.format = :format");
		query.setParameter("format", "counter");
		try {
			Bild bild = (Bild) query.getSingleResult();
			bild.setHits(bild.getHits() + 1);
			em.persist(bild);
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().commit();
			create(new Bild("counter", "", 0, 0, 1, new byte[] {}, 0,
					new byte[] {}, 0, null));
		}
	}

	@Override
	public int getHits() {
		final Query query = this.em
				.createQuery("SELECT b FROM Bild b WHERE b.format = :format");
		query.setParameter("format", "counter");
		query.getSingleResult();
		return ((Bild) query.getSingleResult()).getHits();
	}
}
